package com.example.demo_news.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;


@EnableWebSecurity
// @Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig  extends WebSecurityConfigurerAdapter{
    @Autowired
    private MyUserDetailService myUserDetailService;


    // 自动登录
    // 注入数据源
    @Autowired
    private DataSource dataSource;

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository=new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        // jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    @Bean
    PasswordEncoder password(){return new BCryptPasswordEncoder();}
//密码加密

    @Override 
    protected void configure(AuthenticationManagerBuilder auth)throws Exception{
        auth.userDetailsService(myUserDetailService).passwordEncoder(password());
    }
//验证用户
  
    @Override
    protected void configure(HttpSecurity http)throws Exception{
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/index").permitAll();
        //退出登录
        http.exceptionHandling().accessDeniedPage("/unauth");
        //定义没有访问权限跳转到的页面
        http.formLogin()//自定义自己的登录页面
        .loginPage("/login")//登录页面设置
        .loginProcessingUrl("/toLogin")//登录访问路径
        .defaultSuccessUrl("/index").permitAll()//登陆成功之后,跳转路径
        .and().authorizeRequests()
              .antMatchers("/login","/emailLogin","/register","/index","/unauth","/test","/toRegister").permitAll()//设置哪些路径可以直接访问，不需要认证
              //首页、登录、注册页面、登录注册功能、以及静态资源过滤掉，即可任意访问
		    .antMatchers("/css/**", "/fonts/**", "/js/**","/img/**","/ionicons/**").permitAll()
		      //这里默认追加ROLE_，/user/**是控制器的请求匹配路径
        .anyRequest().authenticated()
        .and().csrf().disable();//关闭csrf防护   
        http.rememberMe()
        .tokenRepository(persistentTokenRepository())
        .tokenValiditySeconds(60000)//设置有效时长
        .userDetailsService(myUserDetailService);
          
    }
}
